'use client';

import { useState } from 'react';

interface Category {
  id: string;
  name: string;
  parentId: string | null;
  children?: Category[];
  path?: string;
  level?: number;
}

interface Props {
  categories: Category[];
  selectedCategory: string | null;
  onSelectCategory: (categoryId: string | null) => void;
}

// 获取分类的图标emoji
const getCategoryIcon = (name: string): string => {
  const iconMap: Record<string, string> = {
    '小学': '📚',
    '初中': '🎓',
    '高中': '✏️',
    '大学': '🎓',
    '四级': '📖',
    '六级': '📘',
    '一年级': '1️⃣',
    '二年级': '2️⃣',
    '三年级': '3️⃣',
    '四年级': '4️⃣',
    '五年级': '5️⃣',
    '六年级': '6️⃣',
    '上学期': '📅',
    '下学期': '📆',
  };
  
  return iconMap[name] || '📝';
};

// 获取分类的渐变背景色（使用HSL颜色，兼容主题）
const getCategoryGradient = (name: string): string => {
  // 使用内联样式来确保颜色正确显示
  const gradientMap: Record<string, { from: string; to: string }> = {
    '小学': { from: 'hsl(35, 80%, 85%)', to: 'hsl(45, 80%, 85%)' },
    '初中': { from: 'hsl(200, 70%, 85%)', to: 'hsl(180, 70%, 85%)' },
    '高中': { from: 'hsl(270, 70%, 85%)', to: 'hsl(330, 70%, 85%)' },
    '大学': { from: 'hsl(150, 70%, 85%)', to: 'hsl(160, 70%, 85%)' },
    '四级': { from: 'hsl(40, 80%, 85%)', to: 'hsl(35, 80%, 85%)' },
    '六级': { from: 'hsl(350, 70%, 85%)', to: 'hsl(330, 70%, 85%)' },
  };
  
  // 根据名称匹配，支持部分匹配
  for (const [key, gradient] of Object.entries(gradientMap)) {
    if (name.includes(key)) {
      return `linear-gradient(135deg, ${gradient.from}, ${gradient.to})`;
    }
  }
  
  // 默认渐变（使用主题色）
  return 'linear-gradient(135deg, hsl(35, 100%, 90%), hsl(45, 80%, 90%))';
};

export default function CategorySelector({ categories, selectedCategory, onSelectCategory }: Props) {
  const [expandedParents, setExpandedParents] = useState<Set<string>>(new Set());

  if (categories.length === 0) {
    return (
      <div className="text-center py-12">
        <p className="text-muted-foreground">暂无分类</p>
      </div>
    );
  }

  const toggleExpand = (categoryId: string) => {
    const newExpanded = new Set(expandedParents);
    if (newExpanded.has(categoryId)) {
      newExpanded.delete(categoryId);
    } else {
      newExpanded.add(categoryId);
    }
    setExpandedParents(newExpanded);
  };

  const renderCategoryCard = (category: Category, isParent: boolean = false) => {
    const isSelected = selectedCategory === category.id;
    const icon = getCategoryIcon(category.name);
    const gradient = getCategoryGradient(category.path || category.name);
    const hasChildren = category.children && category.children.length > 0;
    
    return (
      <div
        key={category.id}
        onClick={() => onSelectCategory(isSelected ? null : category.id)}
        style={{ background: gradient }}
        className={`
          relative group cursor-pointer
          rounded-2xl ${isParent ? 'p-8' : 'p-5'}
          border-2 transition-all duration-300
          ${isSelected 
            ? 'border-primary shadow-lg scale-[1.02]' 
            : 'border-border/50 hover:border-primary/50 hover:shadow-md hover:scale-[1.01]'
          }
          backdrop-blur-sm
          ${isParent ? 'min-h-[140px]' : 'min-h-[100px]'}
        `}
      >
        {/* 选中标记 */}
        {isSelected && (
          <div className="absolute top-3 right-3 w-6 h-6 rounded-full bg-primary flex items-center justify-center">
            <svg className="w-4 h-4 text-primary-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
            </svg>
          </div>
        )}
        
        {/* 图标和名称 */}
        <div className="flex flex-col items-center justify-center space-y-2 h-full">
          <div className={`${isParent ? 'text-6xl' : 'text-4xl'}`}>{icon}</div>
          <div className="text-center w-full">
            <h3 className={`${isParent ? 'text-xl' : 'text-base'} font-semibold ${isSelected ? 'text-foreground' : 'text-foreground/90'}`}>
              {category.name}
            </h3>
            {hasChildren && !isParent && (
              <p className="text-xs text-muted-foreground/70 mt-1">
                {category.children!.length} 个子分类
              </p>
            )}
          </div>
        </div>
        
        {/* 悬停效果 */}
        <div className="absolute inset-0 rounded-2xl bg-primary/0 group-hover:bg-primary/5 transition-colors duration-300 pointer-events-none" />
      </div>
    );
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-semibold mb-2 text-foreground">选择学习分类</h2>
        <p className="text-sm text-muted-foreground">选择一个分类开始你的学习之旅</p>
      </div>
      
      {/* 紧凑的横向滚动布局 */}
      {categories.map((parentCategory) => {
        const hasChildren = parentCategory.children && parentCategory.children.length > 0;
        const isExpanded = expandedParents.has(parentCategory.id);
        const isParentSelected = selectedCategory === parentCategory.id;
        
        return (
          <div key={parentCategory.id} className="space-y-3">
            {/* 父分类 - 紧凑卡片 */}
            <div className="relative">
              <div
                onClick={() => onSelectCategory(isParentSelected ? null : parentCategory.id)}
                style={{ background: getCategoryGradient(parentCategory.path || parentCategory.name) }}
                className={`
                  relative group cursor-pointer
                  rounded-xl p-4
                  border-2 transition-all duration-300
                  ${isParentSelected 
                    ? 'border-primary shadow-md' 
                    : 'border-border/50 hover:border-primary/50 hover:shadow-sm'
                  }
                  backdrop-blur-sm
                  flex items-center gap-4
                `}
              >
                {/* 图标 */}
                <div className="text-4xl flex-shrink-0">
                  {getCategoryIcon(parentCategory.name)}
                </div>
                
                {/* 名称和子分类数量 */}
                <div className="flex-1 min-w-0">
                  <h3 className={`text-lg font-semibold ${isParentSelected ? 'text-foreground' : 'text-foreground/90'}`}>
                    {parentCategory.name}
                  </h3>
                  {hasChildren && (
                    <p className="text-xs text-muted-foreground/70 mt-0.5">
                      {parentCategory.children!.length} 个子分类
                    </p>
                  )}
                </div>
                
                {/* 选中标记 */}
                {isParentSelected && (
                  <div className="w-5 h-5 rounded-full bg-primary flex items-center justify-center flex-shrink-0">
                    <svg className="w-3 h-3 text-primary-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                    </svg>
                  </div>
                )}
                
                {/* 展开/折叠按钮 */}
                {hasChildren && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      toggleExpand(parentCategory.id);
                    }}
                    className="w-8 h-8 rounded-lg bg-background/80 backdrop-blur-sm border border-border hover:bg-accent transition-all duration-300 flex items-center justify-center flex-shrink-0"
                  >
                    <svg 
                      className={`w-4 h-4 text-foreground transition-transform duration-300 ${isExpanded ? 'rotate-180' : ''}`}
                      fill="none" 
                      viewBox="0 0 24 24" 
                      stroke="currentColor"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                )}
              </div>
            </div>
            
            {/* 子分类 - 横向滚动 */}
            {hasChildren && isExpanded && (
              <div className="overflow-x-auto pb-2 -mx-2 px-2">
                <div className="flex gap-3 min-w-max">
                  {parentCategory.children!.map((child) => {
                    const isChildSelected = selectedCategory === child.id;
                    return (
                      <div
                        key={child.id}
                        onClick={() => onSelectCategory(isChildSelected ? null : child.id)}
                        style={{ background: getCategoryGradient(child.path || child.name) }}
                        className={`
                          relative group cursor-pointer flex-shrink-0
                          rounded-xl p-4 w-[140px]
                          border-2 transition-all duration-300
                          ${isChildSelected 
                            ? 'border-primary shadow-md scale-[1.02]' 
                            : 'border-border/50 hover:border-primary/50 hover:shadow-sm hover:scale-[1.01]'
                          }
                          backdrop-blur-sm
                          flex flex-col items-center justify-center
                          min-h-[100px]
                        `}
                      >
                        {/* 选中标记 */}
                        {isChildSelected && (
                          <div className="absolute top-2 right-2 w-5 h-5 rounded-full bg-primary flex items-center justify-center">
                            <svg className="w-3 h-3 text-primary-foreground" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                            </svg>
                          </div>
                        )}
                        
                        {/* 图标和名称 */}
                        <div className="text-3xl mb-2">{getCategoryIcon(child.name)}</div>
                        <h4 className={`text-sm font-semibold text-center ${isChildSelected ? 'text-foreground' : 'text-foreground/90'}`}>
                          {child.name}
                        </h4>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        );
      })}
      
      {selectedCategory && (
        <div className="mt-4 p-3 bg-primary/10 rounded-xl border border-primary/20 backdrop-blur-sm">
          <div className="flex items-center gap-2">
            <svg className="w-4 h-4 text-primary flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p className="text-foreground font-medium text-sm">
              已选择分类，点击上方"开始挑战"按钮开始学习
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

